package com.example.idie.controller;

import com.example.idie.bean.Response;
import com.example.idie.bean.SSHServiceBean;
import com.example.idie.service.SSHService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Controller
public class SSHController {

    @Autowired
    private SSHService sshService;

    @CrossOrigin
    @GetMapping("/usePrivateKey")
    @ResponseBody
    public Response<String> usePrivateKeyLogin() {

        String command = "/data2/suyou/anaconda/myconda/envs/paddle/bin/python -V"; // The command you want to execute
        String host = "amax6.xjtu.io";
        String username = "suyou";
        String privateKeyPath = "C:/Users/yoghurts/.ssh/id_ed25519";
        int port = 47982;

        SSHServiceBean sshServiceBean = new SSHServiceBean(host, port, username, privateKeyPath);
        sshServiceBean.executeCommand(command);

        return Response.success("执行成功");
    }

    @CrossOrigin
    @GetMapping("/useCommand")
    @ResponseBody
    public Response<String> useCommand(@RequestParam("command") String command) {

        String host = "amax6.xjtu.io";
        String username = "suyou";
        String privateKeyPath = "C:/Users/yoghurts/.ssh/id_ed25519";
        int port = 47982;

        SSHServiceBean sshServiceBean = new SSHServiceBean(host, port, username, privateKeyPath);
        sshServiceBean.executeCommand(command);

        return Response.success("执行成功");
    }

    @CrossOrigin
    @PostMapping("/infer")
    @ResponseBody
    public Response<String> infer(@RequestParam("file") MultipartFile file) throws Exception {
        return sshService.infer(file);
    }

    @CrossOrigin
    @GetMapping("/get")
    @ResponseBody
    public Response<String> get(@RequestParam("filename") String fileName, HttpServletResponse response) throws Exception {
        // fileName = TEMP_RESULT.jpg  TEMP.json  TEMP_LOG.log
        return sshService.download(fileName, response);
    }

    @CrossOrigin
    @PostMapping("/train")
    @ResponseBody
    public Response<String> train(@RequestParam("lr") String lr, @RequestParam("epoch") String epoch, @RequestParam("train_path") String train_path) throws Exception {
        Map<String, String> hyperParameters = new HashMap<>();
        hyperParameters.put("lr", lr);
        hyperParameters.put("epoch", epoch);
        hyperParameters.put("train_path", train_path);
        return sshService.train(hyperParameters);
    }
}
